#include "mainwindow.h"
#include <QWebFrame>
//#include <QProgressBar>
MainWindow::MainWindow()
{
    setWindowIcon(QIcon(":/WindowIcon.png"));
    createActions();
    createMenus();
    this->setWindowTitle("Blank");
    centralWidget = new Previewer(this);
    setCentralWidget(centralWidget);
    collector = new Collector("Favorites.xml");
    history = new Collector("History.xml");
    createIcon();
    createTab();
    connect(centralWidget->refButton,SIGNAL(clicked()),this,SLOT(LinkButton()));
    connect(centralWidget->tabWidget->currentWidget(),SIGNAL(loadFinished(bool)),this,SLOT(updateWindowTitle(bool)));

    connect(centralWidget->tabWidget->currentWidget(),SIGNAL(loadProgress(int)),this,SLOT(updateProgressBar(int)));
    connect(centralWidget->backButton,SIGNAL(clicked()),this,SLOT(backWebView()));
    connect(centralWidget->forwardButton,SIGNAL(clicked()),this,SLOT(forwardWebView()));
    //  setStartupText();
    msgLabel = new QLabel;
    msgLabel->setMinimumSize(msgLabel->sizeHint());
    msgLabel->setAlignment(Qt::AlignHCenter);
    statusBar()->addWidget(msgLabel);
    statusBar()->setStyleSheet(QString("QStatusBar::item{border: 0px}"));
    progressBar = new QProgressBar;
    //  progressBar->show();
    progressBar->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Ignored);
    progressBar->setMinimumSize(130,20);
    statusBar()->addWidget(progressBar);
    statusBar()->layout();

    //add main page
    openPage(QString("http://www.g.cn"));
}

void MainWindow::createActions()\
{
    plainAct = new QAction(tr("&Html"),this);
    plainAct->setShortcut(tr("Alt+H"));
    plainAct->setStatusTip(tr("show the page html"));
    connect(plainAct,SIGNAL(triggered()),this,SLOT(updateTextEdit()));

    openAct = new QAction(tr("&Open.."),this);
    openAct->setShortcut(QKeySequence::Open);
    openAct->setStatusTip(tr("Open an existing HTML file"));
    connect(openAct,SIGNAL(triggered()),this,SLOT(open()));

    openUrlAct = new QAction(tr("Open &URL..."),this);
    openUrlAct->setShortcut(tr("Ctrl+U"));
    openUrlAct->setStatusTip(tr("Open a URL"));
    connect(openUrlAct,SIGNAL(triggered()),this,SLOT(openUrl()));

    saveAct = new QAction(tr("&Save"),this);
    saveAct->setShortcut(QKeySequence::Save);
    saveAct->setStatusTip(tr("Save the HTML file"));
    connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));

    exitAct = new QAction(tr("&Exit"),this);
    exitAct->setShortcut(QKeySequence::Quit);
    exitAct->setStatusTip(tr("Exit the Application"));
    connect(exitAct,SIGNAL(triggered()),this,SLOT(close()));

    addcollectAct = new QAction(tr("&AddToCollect"),this);
    addcollectAct->setShortcut(tr("Alt+A"));
    addcollectAct->setStatusTip(tr("Add corrent page to Fav"));
    connect(addcollectAct,SIGNAL(triggered()),this,SLOT(addPage()));

    showcollectAct = new QAction(tr("&ShowCollect"),this);
    showcollectAct->setShortcut(tr("Alt+S"));
    showcollectAct->setStatusTip(tr("Open collect page"));
    connect(showcollectAct,SIGNAL(triggered()),this,SLOT(showPage()));

    showhistoryAct = new QAction(tr("Show&History"),this);
    showhistoryAct->setShortcut(tr("Alt+H"));
    showhistoryAct->setStatusTip(tr("Show history"));
    connect(showhistoryAct,SIGNAL(triggered()),this,SLOT(showHistory()));

    clearhistoryAct =new QAction(tr("Clear History"),this);
    clearhistoryAct->setShortcut(tr("Alt+C"));
    clearhistoryAct->setStatusTip(tr("Clear the history"));
    connect(clearhistoryAct,SIGNAL(triggered()),this,SLOT(clearHistory()));

    aboutAct = new QAction(tr("&About"),this);
    aboutAct->setShortcut(tr("Alt+A"));
    aboutAct->setStatusTip(tr("About the Application"));
    connect(aboutAct,SIGNAL(triggered()),this,SLOT(about()));

    /*  aboutQtAct = new QAction(tr("&QtAbout"),this);
    aboutQtAct->setShortcut(tr("Ctrl+Q"));
    aboutQtAct->setStatusTip(tr("None"));
    connect(aboutQtAct,SIGNAL(triggered()),this,SLOT(about()));*/


}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(openAct);
    fileMenu->addAction(openUrlAct);
    fileMenu->addAction(saveAct);
    fileMenu->addSeparator();
    fileMenu->addAction(plainAct);
    fileMenu->addSeparator(); //add one line
    fileMenu->addAction(exitAct);

    menuBar()->addSeparator();
    collectMenu=menuBar()->addMenu(tr("&Collect"));
    collectMenu->addAction(showcollectAct);
    collectMenu->addAction(addcollectAct);
    collectMenu->addSeparator();
    collectMenu->addAction(showhistoryAct);
    collectMenu->addAction(clearhistoryAct);

    menuBar()->addSeparator();
    helpMenu=menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
    //  helpMenu->addAction(aboutQtAct);

}

void MainWindow::createToolBar()
{
    /*  toolBar = addToolBar(tr("F6"));
    addrBox = new QComboBox;
    addrBox->setStatusTip(tr("Input the web address"));
    // addrBox->setShortcut(tr("F6"));*/

}
void MainWindow::createIcon()
{
    centralWidget->backButton->setIcon(QIcon(":/backIcon.png"));
    centralWidget->forwardButton->setIcon(QIcon(":/forwardIcon.png"));

    QLineEdit *edit=new QLineEdit;
    centralWidget->comboBox->setLineEdit(edit);
    connect(edit,SIGNAL(returnPressed()),this,SLOT(LinkButton()));
    centralWidget->comboBox->setEditable(true);
    centralWidget->comboBox->addItem(QIcon(":/webIcon.png"),"http://");
    //centralWidget->commandLinkButton->setDefault(true);

    centralWidget->refButton->setIcon(QIcon(":/ref.png"));

    coll = new QDockWidget(tr("Favorites"),this);
    coll->hide();
    coll->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    list = new QListWidget;

    plain = new QDockWidget(tr("Html"),this);
    plain->hide();
    coll->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    plainTextEdit = new QPlainTextEdit;


}

void MainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        QFile file(fileName);
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::information(this,tr("Unable to open file"),file.errorString());

            return;
        }

        QTextStream out(&file);
        QString output = out.readAll();
       plainTextEdit->setPlainText(output);
    }
}

void MainWindow::openUrl()
{
    bool ok;
    QString url = QInputDialog::getText(this,tr("Enter a URL"),tr("URL:"),QLineEdit::Normal,"http://",&ok);
    if(ok && !url.isEmpty())
    {
        if(url.at(0)!='h')
            url ="http://"+url;
        mainWebView->setUrl(url);

    }

}

void MainWindow::openPage(QString addr)
{
    if(!addr.isEmpty())
    {

        QUrl url(addr);
        if(url.isValid())
            mainWebView->setUrl(url);
    }
}

void MainWindow::openHistory(QString addr)
{
    if(!addr.isEmpty() && addr.at(0)=='h')
    {
        QUrl url(addr);
        if(url.isValid())
            mainWebView->setUrl(url);
    }
}

void MainWindow::showPage()
{
    coll->show();
    if(collector->readFile())
    {
        list->clear();
        QMapIterator<QString,QString> i(collector->getList());
        while(i.hasNext())
        {
            i.next();
            list->addItem(new QListWidgetItem(i.key()));
            list->addItem(new QListWidgetItem(i.value()));
        }
        connect(list,SIGNAL(currentTextChanged(QString)),this,SLOT(openPage(QString)));
    }
    coll->setObjectName("Fav");
    coll->setWidget(list);

    addDockWidget(Qt::LeftDockWidgetArea,coll);

}

void MainWindow::addPage()
{
   collector->readFile();

   QString name=mainWebView->title();
   QString address=mainWebView->url().toString();
   if(!name.isEmpty() && !address.isEmpty())
       if(collector->writeFile(name,address))
       {
            showPage();
            QMessageBox::information(NULL,"Success","Successful add this Page");
                return;
       }


  QMessageBox::information(NULL,"Failed","Failed add this Page");

}

void MainWindow::showHistory()
{
    history->readFile();
    QMapIterator<QString,QString> i(historyList);
    while(i.hasNext())
    {
        i.next();
        if(!i.key().isEmpty() && !i.value().isEmpty())
           history->writeFile(i.key(),i.value());
    }
    historyList.clear();
    coll->show();
    if(history->readFile())
    {
        list->clear();
        QMapIterator<QString,QString> i(history->getList());
        while(i.hasNext())
        {
            i.next();
            list->addItem(new QListWidgetItem(i.key()));
            list->addItem(new QListWidgetItem(i.value()));
        }

        connect(list,SIGNAL(currentTextChanged(QString)),this,SLOT(openHistory(QString)));
    }
    coll->setObjectName("History");
    coll->setWidget(list);

    addDockWidget(Qt::LeftDockWidgetArea,coll);
}

void MainWindow::clearHistory()
{
    historyList.clear();
    history->clearList();
    history->writeFile("","");
    showHistory();
}

void MainWindow::LinkButton()
{
    //
    QString addr = centralWidget->comboBox->currentText();
    if(!addr.isEmpty())
    {
        if(addr.at(0)!='h')
            addr ="http://"+addr;
        QUrl url(addr);
        if(url.isValid())
        {
            mainWebView->setUrl(url);
        }
    }

}

void MainWindow::save()
{
    QString content = plainTextEdit->toPlainText();
    QString fileName = QFileDialog::getSaveFileName(this);
    if(!fileName.isEmpty())
    {
        QFile file(fileName);
        if(!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::information(this,tr("Unable to save file"),file.errorString());
            return;
        }
        QTextStream in(&file);
        in<<content;
    }
}

void MainWindow::backWebView()
{
    mainWebView->back();

}

void MainWindow::forwardWebView()
{
    mainWebView->forward();
    //QString addr = centralWidget->webView->url().path();
    //centralWidget->comboBox->addItem(addr);
}

void MainWindow::updateTextEdit()
{
    plain->show();
    QWebFrame *mainFrame = mainWebView->page()->mainFrame();
    QString frameText = mainFrame->toHtml();
    plainTextEdit->setPlainText(frameText);
    plain->setObjectName("Html");
    plain->setWidget(plainTextEdit);

    addDockWidget(Qt::LeftDockWidgetArea,plain);

}

void MainWindow::updateWindowTitle(bool flag)
{
    if(flag){
        QString title = mainWebView->title();
        setWindowTitle(title);

        QString addr = mainWebView->url().toString();
        centralWidget->comboBox->setEditText(addr);
        centralWidget->tabWidget->setTabText(centralWidget->tabWidget->currentIndex(),title);
        historyList.insert(title,addr); // add name and title to historyList
    }
}

void MainWindow::updateProgressBar(int a)
{
    progressBar->setValue(a);
}


void MainWindow::about()
{
    QMessageBox::about(this,"About","This Web Browser Create by ymsheng");
}


void MainWindow::closeEvent(QCloseEvent *event)
{
//before close window store history to xml

    QMapIterator<QString,QString> i(historyList);
    while(i.hasNext())
    {
        i.next();
        if(!i.key().isEmpty() && !i.value().isEmpty())
           history->writeFile(i.key(),i.value());
    }
    historyList.clear();


}

void MainWindow::createTab()
{
   QWebView *webView=new QWebView;
   webView->setUrl(QUrl("www.g.cn"));
   centralWidget->tabWidget->addTab(webView,"Google");
        QWebView *newWebView = new QWebView;
       centralWidget->tabWidget->addTab(newWebView,tr("connecting..."));
   connect(newWebView,SIGNAL(loadFinished(bool)),this,SLOT(updateWindowTitle(bool)));
   connect(newWebView,SIGNAL(loadProgress(int)),this,SLOT(updateProgressBar(int)));

   mainWebView = webView;
   centralWidget->tabWidget->setTabsClosable(true);
   connect(centralWidget->tabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(removeTab(int)));
   connect(centralWidget->tabWidget,SIGNAL(currentChanged(int)),this,SLOT(tabChanged(int)));

}

void MainWindow::tabChanged(int index)
{
    mainWebView=qobject_cast<QWebView*>(centralWidget->tabWidget->currentWidget());

    if(centralWidget->tabWidget->count()==index+1)
    {
        QWebView *newWebView = new QWebView;
       centralWidget->tabWidget->addTab(newWebView,tr("connecting..."));

        setWindowTitle("Black");
        centralWidget->comboBox->setEditText("http://");
   connect(newWebView,SIGNAL(loadFinished(bool)),this,SLOT(updateWindowTitle(bool)));
   connect(newWebView,SIGNAL(loadProgress(int)),this,SLOT(updateProgressBar(int)));

    }
    else
    {
     //   QWebView wb(centralWidget->tabWidget->currentWidget());
        QString title =mainWebView->title();
        QString addr = mainWebView->url().toString();

        centralWidget->tabWidget->setTabText(index,title);
        setWindowTitle(title);
        centralWidget->comboBox->setEditText(addr);

        historyList.insert(title,addr);
    }
}

void MainWindow::removeTab(int index)
{
    if(centralWidget->tabWidget->currentIndex()==index)
    {

        QString title =mainWebView->title();
        QString addr = mainWebView->url().toString();

        historyList.insert(title,addr);
        centralWidget->tabWidget->removeTab(index);
	if(centralWidget->tabWidget->count()==2)
    		this->close();
    }
    
}
